<?php
  setcookie('username','user'.rand(10000,99999));
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>客服功能——客服人员端</title>
    <link rel="stylesheet" href="">
    <script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script>
    <script>
        //咨询方法
        function ask(){
            var askContent = $('#askContent').val();
            if(askContent == ''){
                alert('请输入咨询内容');
                return ;
            }
            $.post('./kefu-sendmsg.php',{rec:'admin',content:askContent},function(res){
                if(res == 'ok'){
                    $('<p style="text-align:right">你对客服说：'+askContent+'</p>').appendTo($('#chatArea'));
                    $('#askContent').val('');
                }
          });
        }
    </script>
    <style>
        #chatArea{
            width:500px;
            height:400px;
            border:1px solid black;
            overflow: scroll;
        }
    </style>
</head>
<body>
    <h1>客服功能——用户端</h1>
    <h2>原理：ajax+长连接+长轮询</h2>
    <div id="chatArea">
    </div>
    <p><textarea id="askContent"></textarea></p>
    <p><input type="button" value="咨询" onclick="ask();" /></p>
</body>
<script>
    //长连接+长轮询
    var setting = {
        url:'kefu-ajax.php',
        dataType:'json',
        success:function(res){
        $('<p style="text-align:left">客服对你说：'+res.content+'</p>').appendTo($('#chatArea'));
            var func = function(){$.ajax(setting)};
            window.setTimeout(func,1000);//延时1s后重新发送连接
        }
    }
    $.ajax(setting);
</script>
</html>